package ch15;


/**
 * Created by hasee on 2017/10/18.
 */


public class LinkedQueue<T> implements Queue<T> {
    private int count;
    private LinearNode<T> front, rear;


    public LinkedQueue() {
        count = 0;
        front = rear = null;
    }


    public void enqueue(T element) {
        LinearNode<T> node = new LinearNode<T>(element);

        if (isEmpty())
            front = node;
        else
            rear.setNext(node);

        rear = node;
        count++;
    }


    public T dequeue() throws EmptyStackException {
        if (count == 0)
            throw new EmptyStackException("Queue is empty");
        T result = front.getElement();
        front = front.getNext();
        count--;
        if (count == 0)
            rear = null;

        return result;
    }


    public T first() {
        if (count == 0)
            System.out.println("Error.");
        return front.getElement();
    }


    public boolean isEmpty() {
        return (count == 0);
    }

    public int size() {
        return count;
    }


    public String toString() {
        String result = "";
        LinearNode<T> current =  front;
        while (current != null) {
            result += current.getElement().toString() + "";
            current = current.getNext();
        }
        return result;
    }
}
